package com.kaguya.mediator;

/**
 * 中介者模式(仲裁者模式)，减少各个类之间的复杂通信，提供一个中介者，统一管理和调度各个类，减少耦合
 */
public class Test {
    public static void main(String[] args) {
        // 实例化被调度者并注册到中介者去
        Colleague1 colleague1 = new Colleague1();
        Colleague2 colleague2 = new Colleague2();

        MyMediator mediator = new MyMediator(colleague1,colleague2);
        // 注册成功后调用自己方法即被中介者托管
        colleague1.onEvent(mediator);
        colleague2.onEvent(mediator);
        System.out.println("-----------------");
        mediator.doAllThings();
    }
}

/**
 * 同事抽象类
 */
abstract class Colleague {
    /**
     * 其实现类传入自己的标识，交给mediator去处理实现
     * @param mediator
     */
    public abstract void onEvent(Mediator mediator);
}

/**
 * 中介者抽象类
 */
abstract class Mediator {
    /**
     * 其他同事实现类组合Mediator，执行方法时，由mediator集中管理调度
     */
    public abstract void doEvent(String name);
}

/**
 * 同事实现类1
 */
class Colleague1 extends Colleague {

    @Override
    public void onEvent(Mediator mediator) {
        mediator.doEvent("coll1");
    }

    /**
     * 实际该类负责做的事情，只不过交给了mediator去调用
     */
    public void doMyEvent() {
        System.out.println("hello my bro");
    }
}

/**
 * 同事实现类2
 */
class Colleague2 extends Colleague {

    @Override
    public void onEvent(Mediator mediator) {
        mediator.doEvent("coll2");
    }

    /**
     * 实际该类负责做的事情，只不过交给了mediator去调用
     */
    public void doMyEvent() {
        System.out.println("Have a nice day");
    }
}

/**
 * 中介者实现，组合所有的同事，并按需集中管理他们
 */
class MyMediator extends Mediator {

    private Colleague1 colleague1;

    private Colleague2 colleague2;

    public MyMediator(Colleague1 colleague1, Colleague2 colleague2) {
        this.colleague1 = colleague1;
        this.colleague2 = colleague2;
    }

    @Override
    public void doEvent(String name) {
        switch (name) {
            case "coll1":
                doColleague1Event();
            break;
            case "coll2":
                doColleague2Event();
            break;
            default:
                System.out.println("nothing to do");
            break;
        }
    }

    private void doColleague1Event() {
        System.out.println("命令coll1 去做他的事情");
        colleague1.doMyEvent();
    }

    private void doColleague2Event() {
        System.out.println("命令coll2 去做他的事情");
        colleague2.doMyEvent();
    }

    public void doAllThings() {
        colleague1.doMyEvent();
        colleague2.doMyEvent();
    }
}